package com.example.taskbuilder

import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.app.TaskStackBuilder

class Tservice : Service() {
    var i = 15
    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        showNotification()
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onCreate() {
        super.onCreate()
    }

    private fun showNotification() {
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        //启动通知Activity时，拉起主页面Activity
        val msgIntent = Intent()
        msgIntent.setClass(this, ChildActivity::class.java!!)

        //创建返回栈
        val stackBuilder = TaskStackBuilder.create(this)
        //添加Activity到返回栈
        stackBuilder.addParentStack(ChildActivity::class.java)
        //添加Intent到栈顶
        stackBuilder.addNextIntent(msgIntent)

        val pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)

        // create and send notificaiton
        val mBuilder = NotificationCompat.Builder(this)
            .setLargeIcon(
                BitmapFactory.decodeResource(
                    resources,
                    R.drawable.ic_launcher_foreground
                )
            )
            .setSmallIcon(applicationInfo.icon)
            .setWhen(System.currentTimeMillis())
            .setAutoCancel(true)//自己维护通知的消失
            .setContentTitle("我是标题")
            .setTicker("我是ticker")
            .setContentText("我是内容")
            .setContentIntent(pendingIntent)
            .setChannelId(""+i)
        //将一个Notification变成悬挂式Notification
        mBuilder.setFullScreenIntent(pendingIntent, true)
        val notification = mBuilder.build()
        manager.notify(i++, notification)


        //把该service创建为前台service
//        startForeground(i++, notification);

    }
}